package com.leilei.dao.impl;

import com.leilei.dao.ICommodityColor;
import com.leilei.entity.CommodityColor;
import com.leilei.util.DBUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class CommodityColorImpl implements ICommodityColor {

    private QueryRunner queryRunner = new QueryRunner(DBUtil.getDataSource());

    @Override
    public List<CommodityColor> selectCommodityColorByPid(int pid) {

        try {
            return queryRunner.query("select pcid, pid, colorname, pdefault from commoditycolor where pid = ?",
                    new BeanListHandler<CommodityColor>(CommodityColor.class), pid);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return null;
    }

    @Override
    public CommodityColor selectCommodityColorByPcid(int pcid) {

        try {
            return queryRunner.query("select pcid, pid, colorname, pdefault from commoditycolor where pcid = ?",
                    new BeanHandler<CommodityColor>(CommodityColor.class), pcid);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return null;
    }

    @Override
    public int insertCommodityColor(CommodityColor commodityColor) {

        String sql = "insert into commoditycolor(pid, colorname) values (?, ?)";

        try {
            return queryRunner.update(sql,
                    commodityColor.getPid(),
                    commodityColor.getColorname());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return 0;
    }

    @Override
    public int deleteCommodityColor(int pcid) {

        String sql = "delete from commoditycolor where pcid = ?";

        try {
            return queryRunner.update(sql, pcid);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return 0;
    }

    @Override
    public int updateCommodityColor(CommodityColor commodityColor) {

        String sql = "update commoditycolor set colorname = ? where pcid = ?";

        try {
            return queryRunner.update(sql, commodityColor.getColorname(), commodityColor.getPcid());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return 0;
    }
}
